import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/mock_api.dart';
import 'package:music_app/widget/play_list_cover.dart';
import 'package:music_app/widget/text_icon_button.dart';

class RecommentRankList extends StatefulWidget {
  const RecommentRankList({super.key});

  @override
  State<RecommentRankList> createState() => _RecommentRankListState();
}

class _RecommentRankListState extends State<RecommentRankList> {
  // 推荐歌单列表
  List<dynamic> _playList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  Future<void> getData() async {
    try {
      final response = await MockApi.fetchRecommendSongList();
      final List<dynamic> playList = response['result'];
      setState(() {
        _playList = playList.take(6).toList(); // 只取前 6 条
      });
    } catch (e) {
      setState(() {
        _playList = []; // 只取前 9 条
      });
    } finally {}
  }

  @override
  Widget build(BuildContext context) {
    double width = (MediaQuery.of(context).size.width - 100) / 3;
    double height = width + 8 + 48 + 12; // 图片 + 间距 + 文本高度（大概估值）加上12的底部边距
    // 根据PlaylistCover组件内的组件来计算的 文本的高度 是 文字和行高 文字是14 我们 * 2 取28
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextIconButton(
          text: '排行榜',
          onTap: () {},
        ),
        const SizedBox(height: 8),
        SizedBox(
          height: height,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: _playList.length,
            itemBuilder: (context, index) {
              return Container(
                width: width,
                margin: const EdgeInsets.only(right: 8),
                child: PlaylistCover(
                  width: width,
                  height: width,
                  imageUrl: _playList[index]['picUrl'],
                  title: _playList[index]['name'],
                  onTap: () {
                    Get.toNamed(
                      '/playlist',
                      arguments: {
                        'id': _playList[index]['id'],
                      },
                    );
                  },
                  onPlayTap: () {},
                ),
              );
            },
          ),
        )
      ],
    );
  }
}
